import { InjectionKey, inject, reactive } from 'vue'
import { WidgetConfig } from './WidgetProtocol'

export interface PropertyEditorContext {
  config: WidgetConfig
  path: string[]
  disabled?: boolean
}

export interface PropertyEditorHandle {
  validate: () => boolean
  getValue: () => any
  setValue: (value: any) => void
}

export const PropertyEditorContextKey: InjectionKey<PropertyEditorContext> = Symbol('property-editor-context')

export class PropertyEditorRegistry {
  private editors = new Map<string, any>()

  registerEditor(type: string, component: any) {
    this.editors.set(type, component)
  }

  getEditor(type: string) {
    return this.editors.get(type)
  }
}

export function usePropertyEditor() {
  const context = inject(PropertyEditorContextKey)!
  const state = reactive({
    value: getNestedValue(context.config, context.path),
    error: null as string | null
  })

  const validate = () => {
    // 实际验证逻辑需要根据字段类型实现
    return true
  }

  return {
    state,
    validate,
    setValue: (value: any) => {
      setNestedValue(context.config, context.path, value)
      state.value = value
    }
  }
}

function getNestedValue(obj: any, path: string[]) {
  return path.reduce((o, k) => (o || {})[k], obj)
}

function setNestedValue(obj: any, path: string[], value: any) {
  path.reduce((o, k, i) => {
    if (i === path.length - 1) {
      o[k] = value
    } else if (!o[k]) {
      o[k] = {}
    }
    return o[k]
  }, obj)
}